<template>
  <div>
    <el-drawer
      :title="title"
      :visible.sync="drawerVisible"
      direction="rtl"
      :before-close="handleClose"
    >
      <div ref="oilRef" class="demo-drawer__content">
        <el-form
          :model="goodsForm"
          :rules="goodsFormRules"
          ref="goodsRuleFormRef"
          style="padding: 0rem 2rem"
        >
          <h5>商品-基础信息</h5>
          <el-form-item
            prop="name"
            label="商品名称"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="goodsForm.name"
              autocomplete="off"
              size="medium"
              placeholder="请输入商品名称"
              :disabled="isShowDetail"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品ID" :label-width="formLabelWidth">
            <el-input
              disabled
              placeholder="无需输入，系统自动生成"
              size="medium"
              :value="goodsForm.id"
            ></el-input>
          </el-form-item>
          <el-form-item
            prop="consumedPoint"
            label="消耗积分"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="goodsForm.consumedPoint"
              autocomplete="off"
              placeholder="请输入兑换所需积分"
              size="medium"
              :disabled="isShowDetail"
            ></el-input>
          </el-form-item>
          <el-form-item prop="stock" label="库存" :label-width="formLabelWidth">
            <el-input
              v-model="goodsForm.stock"
              :disabled="isShowDetail"
              autocomplete="off"
              size="medium"
              style="width: 200px; margin-right: 1rem"
              placeholder="请输入商品数量"
            ></el-input
            >个
          </el-form-item>
          <el-form-item
            prop="imgList"
            label="商品图片"
            :label-width="formLabelWidth"
          >
            <el-upload
              :file-list="fileImgList"
              :action="imgUpConfig.addressUrl"
              :headers="imgUpConfig.headers"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :before-upload="beforeAvatarUpload"
              :on-success="handleAvatarSuccess"
              :disabled="isShowDetail"
            >
              <i class="el-icon-plus"></i>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件,且不超过5M
              </div>
            </el-upload>
            <el-dialog :visible.sync="imgListDialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </el-form-item>
          <el-form-item
            prop="remark"
            label="商品描述"
            :label-width="formLabelWidth"
          >
            <el-input
              type="textarea"
              v-model="goodsForm.remark"
              autocomplete="off"
              :autosize="{ minRows: 4 }"
              placeholder="请输入商品描述"
              :disabled="isShowDetail"
            ></el-input>
          </el-form-item>

          <h5 style="margin-top: 3rem; margin-bottom: 1rem">商品-关联站点</h5>
          <!-- admin账号： 可选择所有的油企 -->
          <el-form-item
            v-if="authUser"
            prop="enterpriseId"
            label="油企名"
            :label-width="formLabelWidth"
          >
            <el-select
              v-model="goodsForm.enterpriseId"
              placeholder="请选择油企"
              size="small"
              style="width: 250px"
              filterable
              clearable
              @change="handleSelectChangeAddOrEdit"
              :disabled="isShowDetail"
            >
              <el-option
                v-for="(item, index) in enterpriseList"
                :key="index"
                :label="item.enterpriseName"
                :value="item.enterpriseId"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 不是admin账号: 油企只能选择自己的 -->
          <el-form-item
            v-if="!authUser"
            prop="enterpriseId"
            label="油企名"
            :label-width="formLabelWidth"
          >
            <el-select
              prop="enterpriseId"
              v-model="goodsForm.enterpriseId"
              placeholder="请选择油企"
              :disabled="isShowDetail"
            >
              <el-option
                :label="presentEnterprise.enterpriseName"
                :value="presentEnterprise.enterpriseId"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            prop="stationId"
            label="油站名"
            :label-width="formLabelWidth"
          >
            <el-select
              v-model="goodsForm.stationId"
              placeholder="请选择油站"
              size="small"
              style="width: 250px"
              filterable
              clearable
              :disabled="isShowDetail"
            >
              <el-option
                v-for="item in stationList"
                :key="item.stationId"
                :label="item.stationName"
                :value="item.stationId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item style="text-align: end">
            <div class="demo-drawer__footer">
              <el-button @click="cancelForm">取 消</el-button>
              <el-button
                type="primary"
                @click="handelSubmit"
                v-show="isShowDetail == false"
                >确定</el-button
              >
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  listEnterpriseStation,
  getEnterpriseList,
  addNonOilGoodsInfoApi,
  editNonOilGoodInfoAPi,
  getNonOilGoogInfoByIdApi,
  changeNonOilGoodStatusApi,
} from "@/api/dept";
import { getToken } from "@/utils/auth";
export default {
  name: "DeptNonOilDrawer",
  props: {
    drawerVisible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: "标题",
    },
    operationType: {
      type: String,
      default: "操作类型", // 值有add , edit , detail
    },
    currentRowData: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      formLabelWidth: "80px",
      imgListDialogVisible: false,
      fileImgList: [],
      dialogImageUrl: "",
      enterpriseList: [],
      stationList: [],
      imgUpConfig: {
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        addressUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      },
      // 添加或编辑商品
      goodsForm: {
        name: "", // 商品名称
        consumedPoint: "", //消耗积分
        stock: "", // 库存
        remark: "", //描述
        enterpriseId: "", // 油企id
        stationId: "", // 油站id
        image: "", // 图片字符串
      },
      goodsFormRules: {
        name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        consumedPoint: [
          { required: true, message: "请输入兑换所需积分", trigger: "blur" },
        ],
        stock: [{ required: true, message: "请输入库存", trigger: "blur" }],

        enterpriseId: [
          { required: true, message: "请选择油站", trigger: "change" },
        ],
        stationId: [
          { required: true, message: "请选择油站名称", trigger: "change" },
        ],
      },
    };
  },
  computed: {
    authUser() {
      // 判断用户是否是admin账号
      let roles = this.$store.state.user.roles;
      if (roles.includes("admin")) {
        return true;
      } else {
        return false;
      }
    },
    isShowDetail() {
      return this.operationType === "detail";
    },
  },
  created() {
    console.log(this, "666");
    // 获取油企列表
    this.getEnterpriseList();
    // 如果当前是油企账号，则获取该企业下的油站  presentEnterprise是全局的对象数据
    if (this.presentEnterprise && this.presentEnterprise.enterpriseId) {
      this.getStationList(this.presentEnterprise.enterpriseId);
    }
  },
  watch: {
    currentRowData: {
      handler(row) {
        // 重置一下表单数据
        this.resetForm("goodsRuleFormRef");
        if (row.id) {
          // 获取商品信息
          console.log("触发请求了吗", row);
          this.getDetailInfo(row.id); // 获取商品详细信息
        }
      },
      immediate: true,
      deep: true,
    },
    drawerVisible(value) {
      // 每次一打开右侧，删除一下id，防止新增时候，由于保留id，执行了编辑操作
      console.log(value, "drawerVisible");
      if (this.goodsForm.id) {
        this.$delete(this.goodsForm, "id");
      }
    },
  },
  methods: {
    // 获取商品详细信息
    async getDetailInfo(id) {
      const res = await getNonOilGoogInfoByIdApi(id);
      // 然后再获取一下对应的油站列表
      await this.getStationList(res.data.enterpriseId);
      // 回显图片列表
      let temImgs = res.data.image;
      temImgs = temImgs.split(",");
      // 给每个组成 {name:xxx,url:xxx} , 组件根据 name 和 url 渲染图片
      temImgs = temImgs.map((item) => {
        return {
          name: item,
          url: item,
        };
      });
      this.fileImgList = temImgs;
      this.goodsForm = res.data;
      console.log(res, "获取商品详情");
    },

    // 确认提交
    handelSubmit() {
      this.$refs["goodsRuleFormRef"].validate(async (valid) => {
        if (valid) {
          if (this.operationType === "add") {
            // 新增商品
            // 统一处理图片,并转换成字符串格式传给后端
            const params = { ...this.goodsForm };
            if (this.fileImgList.length) {
              let imgList = this.fileImgList.map((item) => {
                return item.response.url;
              });
              params.image = imgList.join(",");
            }
            await addNonOilGoodsInfoApi(params).then((res) => {
              this.msgSuccess("添加非油品管理成功");
            });
          }
          if (this.operationType === "edit") {
            {
              // 编辑商品
              // 统一处理img。有一些可能是后台接口返回来的格式，有一些可能是新上传的
              let temImgs = this.fileImgList;
              if (temImgs.length) {
                let temImgList = temImgs.map((item) => {
                  if (item.response) {
                    // 新上传的
                    return item.response.url;
                  } else {
                    // 原本调接口返回来的
                    return item.url;
                  }
                });
                this.goodsForm.image = temImgList.join(",");
                await editNonOilGoodInfoAPi(this.goodsForm).then((res) => {
                  this.msgSuccess("编辑非油品管理成功");
                });
              }
            }
          }
          // 如果当前编辑的商品是已下架的商品时，编辑之后修改商品状态为待上架
          if (this.currentRowData.status === 2) {
            await changeNonOilGoodStatusApi(this.currentRowData.id, 1);
          }

          // 置空form的照片墙
          this.fileImgList = [];
          this.$emit("update:drawerVisible", false);
          this.$emit("reloadData");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 查询油企列表
    getEnterpriseList() {
      getEnterpriseList().then((res) => {
        this.enterpriseList = res.rows;
      });
    },
    // 获取油站列表
    async getStationList(enterpriseId) {
      const res = await listEnterpriseStation({ enterpriseId: enterpriseId });
      this.stationList = res;
    },

    // 切换油企： 置空油站，重新获取油站数据
    handleSelectChangeAddOrEdit(val) {
      this.goodsForm.stationId = null;
      this.getStationList(val);
    },
    // 点击外部区域关闭抽屉 ： 清空照片墙，关闭抽屉， 重置表单（否则下次再点击相同一行进来的时候，数据没有变化，不会重新发请求）
    handleClose() {
      this.fileImgList = [];
      this.$emit("update:drawerVisible", false);
      this.$emit("resetCurrentRowData");
    },

    // 取消按钮关闭抽屉 ： 关闭抽屉，并清空图片列表
    cancelForm() {
      this.$emit("update:drawerVisible", false);
      this.$emit("resetCurrentRowData");
      this.fileImgList = [];
      clearTimeout(this.timer);
    },

    // 图片上传前的校验
    beforeAvatarUpload(file) {
      const imgtypes = ["image/jpeg", "image/png"];
      if (!imgtypes.includes(file.type)) {
        this.msgError("图片只能是jpg或png格式");
        return false;
      }
      let isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.msgError("图片大小不能超过5m");
        return false;
      }
    },
    // 图片上传成功时
    handleAvatarSuccess(res, file, fileList) {
      console.log("图片上传成功", fileList);
      this.fileImgList = fileList;
      this.imageUrl = URL.createObjectURL(file.raw);
    },

    // 删除图片: 同步更新fileImgList
    handleRemove(file, fileList) {
      this.fileImgList = fileList;
    },

    // 预览图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.imgListDialogVisible = true;
    },
  },
};
</script>

<style scoped></style>
